import router from './router'
import store from './store'
import { Message } from 'element-ui'
import 'nprogress/nprogress.css' // progress bar style
import nProgress from 'nprogress'
import { asyncRoutes } from '@/router/index'
// import { getToken } from '@/utils/auth' // get token from cookie
// import getPageTitle from '@/utils/get-page-title'

router.beforeEach(async(to, from, next) => {
  nProgress.start()
  const whiteList = ['/login', '/404']
  const token = store.state.user.token
  if (token) {
    if (to.path === '/login') {
      Message.error('已经登录了哈')
      next('/')
      nProgress.done()
    } else {
      document.title = `人力资源管理系统-${to.meta.title}`
      if (!store.state.user.userInfo.userId) {
        const menus = await store.dispatch('user/getUserInfo')
        console.log(menus, '00')
        const filterRoutes = asyncRoutes.filter(route => {
          return menus.includes(route.children[0].name)
        })
        filterRoutes.push({ path: '*', redirect: '/404', hidden: true })
        router.addRoutes(filterRoutes)
        store.commit('menus/setMenus', filterRoutes)
        next({ ...to, replace: true })
      } else {
        next()
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      Message.error('还没有登录')

      next('/login')
      nProgress.done()
    }
  }
})
router.afterEach(() => {
  nProgress.done()
})

